#!/usr/bin/python3

import configparser
import optparse
import os.path
import datetime # for benchmarking

import classes.storages as storages
import classes.connects as connects

if __name__ == '__main__':

    config_parser = configparser.SafeConfigParser()
    config_parser.read(os.path.join(os.path.dirname(__file__), 'config.ini'))

    option_parser = optparse.OptionParser()
    option_parser.add_option("--storage-host", type="str", dest="storage_host", default = config_parser.get('storage', 'host'), help="")
    option_parser.add_option("--storage-port", type="int", dest="storage_port", default = config_parser.get('storage', 'port'), help="")
    option_parser.add_option("--storage-user", type="str", dest="storage_user", default = config_parser.get('storage', 'user'), help="")
    option_parser.add_option("--storage-pass", type="str", dest="storage_pass", default = config_parser.get('storage', 'pass'), help="")
    option_parser.add_option("--storage-base", type="str", dest="storage_base", default = config_parser.get('storage', 'base'), help="")
    option_parser.add_option("--path-ingames", type="str", dest="path_ingames", default = config_parser.get('path', 'ingames'), help="")
    option_parser.add_option("--path-archive", type="str", dest="path_archive", default = config_parser.get('path', 'archive'), help="")
    option_parser.add_option("--path-exports", type="str", dest="path_exports", default = config_parser.get('path', 'exports'), help="")
    option_parser.add_option("-f", "--from"  , type="int", dest="from_length" , default =  1, help="From what length to start, inclusive")
    option_parser.add_option("-t", "--till"  , type="int", dest="till_length" , default = 20, help="Till what length to work, inclusive" )
    option_parser.add_option("-p", "--purge" , action="store_true", dest="purge", default=False)
    (options, params) = option_parser.parse_args()

    db = connects.Db(**options.__dict__)

    trips = storages.Trips(db)

    if options.purge:
        print("Purging...")
        db.start()
        trips.drop()
        trips.create()
        trips.prefill()
        db.commit()

    (last_count, max_length, min_length) = trips.stats()
    print("Initially there are %d trips, maximum length = %d." % (last_count, max_length))

    for length in range(options.from_length, options.till_length + 1):

        print("Calculating trips with length %2d..." % length, end='')

        s = datetime.datetime.now()

        try:
            db.start()
            trips.augmentTo(length)
            db.commit()
        except Exception as exception:
            db.rollback()
            raise exception

        e = datetime.datetime.now()
        d = e - s

        (new_count, dummy, dummy) = trips.stats()
        print(" got %7d new trips, and now there are %7d trips totally, time=%03.6f secs." % (new_count - last_count, new_count, d.days*24*60*60 + d.seconds + d.microseconds/1000000))
        last_count = new_count

    print("Analyzing...")
    trips.analyze()

    print("Done!")
